<?php
/**
 * 客户群
 * User: 万奇
 * Date: 2021/10/9 18:01
 */

namespace app\admin\model;


use app\core\Wechat;
use think\facade\Db;

class WxkCustomerGroup extends BasicModel
{
    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }

    /**
     * 客户群打标签/移除标签
     * User: 万奇
     * Date: 2021/11/4 17:05
     * @param $param
     */
    public function customer_group_tagging($param){
        $group      = $this->where([['id', 'in', implode(',', $param['id'])]])->column('tag_ids', 'id');

        foreach ($group as $k => $v){
            if ($param['type'] == 1){
                $update['tag_ids']     = implode(',', $v ? array_unique(array_merge(explode(',', $v), $param['tag_ids'])) : $param['tag_ids']);
            } else{
                $update['tag_ids']     = implode(',', array_diff(explode(',', $v), $param['tag_ids']));
            }

            $this->where(['id' => $k])->update($update);
        }
    }

    /**
     * 编辑群二维码
     * User: 万奇
     * Date: 2021/2/24 0024
     * @param $param
     * @throws \think\db\exception\DbException
     */
    public function edit_customer_group_qr_code($param){
        $time           = time() - 10;
        $result         = $this->where(['id' => $param['id']])->update(['qr_code' => $param['url'], 'media_id' => $param['media_id'], 'created_at' => $time]);

//        // 查询该群是否关联了自动入群
//        $live_qr        = Db::name('wxk_live_qr')->where(['use_customer_group' => $param['id'], 'is_welcome_msg' => 1])->column('id,welcome_data');
//        if ($live_qr){
//            foreach ($live_qr as $v){
//                $text_msg       = json_decode($v['welcome_data']);
//                if (isset($text_msg->attachments[0]->image->pic_url)){
//                    $text_msg->attachments[0]->image->pic_url       = $param['url'];
//                    $text_msg->attachments[0]->image->media_id      = $param['media_id'];
//                    Db::name('wxk_live_qr')->where(['id' => $v['id']])->update(['welcome_data' => json_encode($text_msg)]);
//                }
//            }
//        }

        if (!$result){
            response(500, '操作失败');
        }
    }

    /**
     * 客户群列表详情
     * User: 万奇
     * Date: 2021/2/24 0024
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_customer_group_info($param){
        $group             = $this->where(['id' => $param['id']])->find()->toArray();
        $group['status']   = \StaticData::RESOURCE_NAME['customer_group_status'][$group['status']];
        $group['owner_name']   = Db::name('wxk_staff')->where([['user_id', '=', $group['owner_user_id']]])->value('name');

        $where[]           = ['a.group_id', '=', $param['id']];

        if (is_exists($param['name'], false, true)){
            $name_where    = [['name', 'like', "%{$param['name']}%"]];
            $staff_id      = Db::name('wxk_staff')->where($name_where)->value('user_id');
            $customer_id   = Db::name('wxk_customer')->where($name_where)->value('external_user_id');
            $where[]       = ['a.user_id', 'in', implode(',', array_filter([$staff_id, $customer_id]))];
        }

        $list              = Db::name('wxk_customer_group_member')->alias('a')
            ->field('a.user_id,a.user_type,a.join_scene,a.join_time,b.name invitor')
            ->join('wxk_staff b', "a.invitor=b.user_id", 'left')
            ->where($where)
            ->order(['a.join_time' => 'desc'])
            ->paginate($param['limit'])
            ->toArray();

        foreach ($list['data'] as $k => $v){
            $list['data'][$k]['name']       = Db::name($v['user_type'] == 1 ? 'wxk_staff' : 'wxk_customer')->where([$v['user_type'] == 1 ? 'user_id' : 'external_user_id' => $v['user_id']])->value('name');
            $list['data'][$k]['user_type']  = \StaticData::RESOURCE_NAME['customer_group_user_type'][$v['user_type']];
            $list['data'][$k]['join_scene'] = \StaticData::RESOURCE_NAME['customer_group_join_scene'][$v['join_scene']];
        }

        return ['data' => ['info' => $group, 'list' => $list['data']], 'total' => $list['total']];
    }

    /**
     * 客户群列表
     * User: 万奇
     * Date: 2021/2/24 0024
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function get_customer_group_list($param){
        $where[]          = ['is_dismiss', '=', 0];

        if (is_exists($param['name'])){
            $where[]      = ['name', 'like', "%{$param['name']}%"];
        }

        if (is_exists($param['owner_user_name'])){
            $staff_id     = Db::name('wxk_staff')->where([['name', 'like', "%{$param['owner_user_name']}%"]])->value('user_id');
            if ($staff_id){
                $where[]  = ['owner_user_id', '=', $staff_id];
            }
        }

        $list             = $this->where($where)->order(['status' => 'asc', 'create_at' => 'desc'])->paginate($param['limit'])->toArray();

        $staff            = Db::name('wxk_staff')->where([['user_id', 'in', implode(',', array_column($list['data'], 'owner_user_id'))]])->column('name', 'user_id');
        $tag_name         = Db::name('wxk_customer_tag')->column('name', 'id');

        foreach ($list['data'] as $k => $v){
            $list['data'][$k]['status']         = \StaticData::RESOURCE_NAME['customer_group_status'][$v['status']];
            $list['data'][$k]['owner_name']     = $staff[$v['owner_user_id']];
            $list['data'][$k]['number']         = Db::name('wxk_customer_group_member')->where(['user_type' => 2, 'group_id' => $v['id']])->count();
            $list['data'][$k]['tag_ids']        = get_name_attr($tag_name, $v['tag_ids']);

            // 群名称为空时
            if (empty($v['name'])){
                $group_user_id              = Db::name('wxk_customer_group_member')->where(['group_id' => $v['id'], 'user_type' => 2])->limit(2)->column('user_id');
                $group_user_name            = Db::name('wxk_customer')->distinct('name')->where([['external_user_id', 'in', implode(',', $group_user_id)]])->column('name');
                $list['data'][$k]['name']   = $staff[$v['owner_user_id']] . '、' . implode('、', $group_user_name);
            }
        }

        return $list;
    }

    /**
     * 同步客户群数据
     * User: 万奇
     * Date: 2021/2/24 0024
     * @param string $next_cursor
     * @throws \think\db\exception\DbException
     */
    public function sync_customer_group($next_cursor = ''){
        $wechat             = new Wechat();
        $url                = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list';
        $api_data           = $next_cursor ? ['cursor' => $next_cursor, 'limit' => 100] : ['limit' => 100];
        $list               = $wechat->request_wechat_api($url, 'wxk_customer_admin_secret', $api_data, true, true);

        if ($list['errcode'] != 0){
            response(500, $list['errmsg']);
        }

        // 清除该企业客户群数据
        if ($next_cursor == ''){
            Db::name('wxk_customer_group_member')->where(true)->delete();
        }

        $info_url       = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get';
        foreach ($list['group_chat_list'] as $k => $v){
            $info       = $wechat->request_wechat_api($info_url, 'wxk_customer_admin_secret', ['chat_id' => $v['chat_id']], true, true)['group_chat'];

            $data_group_id   = $this->where(['chat_id' => $v['chat_id']])->value('id');
            if ($data_group_id){
                $this->where(['id' => $data_group_id])->update(['name' => $info['name'], 'status' => $v['status'], 'number' => count($info['member_list']), 'owner_user_id' => $info['owner']]);
            } else{
                $data_group_id      = uuid();
                $this->insert(['id' => $data_group_id, 'chat_id' => $v['chat_id'], 'name' => $info['name'],
                    'status' => $v['status'], 'number' => count($info['member_list']), 'owner_user_id' => $info['owner'],
                    'create_time' => date('Y-m-d H:i:s', $info['create_time'])]);
            }

            $data_member  = [];
            foreach ($info['member_list'] as $m_k => $m_v){
                $data_member[$m_k]['id']          = uuid();
                $data_member[$m_k]['group_id']    = $data_group_id;
                $data_member[$m_k]['user_id']     = $m_v['userid'];
                $data_member[$m_k]['user_type']   = $m_v['type'];
                $data_member[$m_k]['join_scene']  = $m_v['join_scene'];
                $data_member[$m_k]['invitor']     = empty($m_v['invitor']['userid']) ? '' : $m_v['invitor']['userid'];
                $data_member[$m_k]['join_time']   = date('Y-m-d H:i:s', $m_v['join_time']);
            }

            Db::name('wxk_customer_group_member')->insertAll($data_member);
        }

        // 判断是否有分页游标
        if (isset($list['next_cursor'])){
            $this->sync_customer_group($list['next_cursor']);
        }
    }

}